package com.jtj.server.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jtj.server.pojo.Employee;
import com.jtj.server.pojo.MailConstants;
import com.jtj.server.pojo.MailLog;
import com.jtj.server.service.IEmployeeService;
import com.jtj.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReactiveHashCommands;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
public class MailSendTask {
    @Autowired
    IMailLogService mailLogService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    IEmployeeService employeeService;

    /**
     * 10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailResendTask() {
        List<MailLog> logs = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        if (logs == null || logs.size() == 0) {
            return;
        }
        logs.forEach(mailSendLog->{
            if (mailSendLog.getCount() >= 3) {
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2).eq("msgId", mailSendLog.getMsgId()));//直接设置该条消息发送失败
            }else{
                mailLogService.update(new UpdateWrapper<MailLog>().set("count", mailSendLog.getCount()+1)
                        .set("updateTime", LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                        .eq("msgId",mailSendLog.getMsgId()));
                Employee emp = employeeService.getById(mailSendLog.getEid());
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, emp, new CorrelationData(mailSendLog.getMsgId()));
            }
        });
    }
}
